package com.rovinj_server.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.rovinj_server.R;
import com.rovinj_server.adapter.BlindFIAdapter;
import com.rovinj_server.adapter.FIAdapter;
import com.rovinj_server.adapter.PeopleRecyclerAdapter;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.InventorySub;
import com.rovinj_server.entity.InventoryTaskSub;
import com.rovinj_server.entity.People;
import com.rovinj_server.ui.SameActivity;
import com.rovinj_server.utisl.Directory;
import com.rovinj_server.utisl.ExcelUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jxl.write.WriteException;

/**
 * Created by Administrator on 2017/5/11.
 */

public class BlindInventoryFragment extends BaseFragmet implements SwipeRefreshLayout.OnRefreshListener {
    public static final String TAG = "-----InventoryFragment";
    @Bind(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @Bind(R.id.swipe_refresh)
    SwipeRefreshLayout mSwipeRefresh;
    @Bind(R.id.but_submit)
    Button mButSubmit;
    @Bind(R.id.et_search)
    EditText mEtSearch;
    @Bind(R.id.add_qty1)
    TextView mAddQty1;
    @Bind(R.id.add_qty2)
    TextView mAddQty2;
    @Bind(R.id.add_qty3)
    TextView mAddQty3;
    @Bind(R.id.add_qty4)
    TextView mAddQty4;
    private View mView;
    private List<InventorySub> mListSubData = new ArrayList<>();
    private DBManager mDBManager;
    private Context mContext;
    private BlindFIAdapter mAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = View.inflate(getActivity(), R.layout.fragment_inventory, null);
        }
        ButterKnife.bind(this, mView);
        mButSubmit.setText("查看信息");
        mDBManager = new DBManager(getActivity());
        mDBManager.copyDBFile();

        initAdapter();
        return mView;
    }


    private void initAdapter() {
        mSwipeRefresh.setOnRefreshListener(this);
        mSwipeRefresh.setColorSchemeColors(Color.rgb(47, 223, 189));  //设置动漫颜色
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new BlindFIAdapter(mListSubData);

        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT); //设置动漫
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    InventorySub inventorySub = mListSubData.get(position);
                    pop(inventorySub);
                } catch (Exception e) {
                    set_Message(0, "清空");
                }
            }
        });
    }


    private void ini() {
        set_showDialog("获取");
        new Thread(new Runnable() {
            @Override
            public void run() {
                mListSubData = mDBManager.findSubTaskList();
                if (mListSubData != null) {

                }
                set_ColseDialog();
                set_Message(0, "更新UI");
            }
        }).start();

    }

    @Override
    public void onStart() {  //用户可见 调用
        super.onStart();
     //   ini();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    public void set_Message(int what, String obj) {
        Message message = new Message();
        message.what = what;
        message.obj = obj;
        mHandler.sendMessage(message);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                    ui_UpData(obj);
                    break;
            }
        }
    };

    private void ui_UpData(String str) {
        if (str.equals("更新UI")) {
            int qty = 0;
            int discQty = 0;
            int moreQty = 0;
            int lessQty = 0;
            if (mListSubData != null && mListSubData.size() > 0) {
                for (int i = 0; i < mListSubData.size(); i++) {
                    int sj = Integer.parseInt(mListSubData.get(i).getSjnumber());
                    qty = qty + sj;
                    int discNumber = mListSubData.get(i).getDiscNumber();
                    discQty = discQty + discNumber;
                    Log.d(TAG, "-根据条码查询数据  货位信息mListSubData-- " + i);
                    int mtq = mListSubData.get(i).getMoreThan();
                    moreQty = moreQty + mtq;
                    int ltq = mListSubData.get(i).getLessThan();
                    lessQty = lessQty + ltq;
                }
                mAddQty3.setText(moreQty + "");
                mAddQty2.setText(lessQty + "");
                mAddQty4.setText((qty + ""));
                mAddQty1.setText((discQty + ""));
                mAdapter.setNewData(mListSubData);
                mAdapter.loadMoreComplete();//刷新
                return;
            } else {
                //提示 用户 没找到对应 货位信息
                set_Toast("----暂无找到该货位信息");
                mAddQty3.setText("0");
                mAddQty2.setText("0");
                mAddQty4.setText("0");
                mAddQty1.setText("0");
                return;
            }

        }  else if (str.equals("清空")) {
            mAddQty3.setText("0");
            mAddQty2.setText("0");
            mAddQty4.setText("0");
            mAddQty1.setText("0");
            mListSubData.clear();
            mAdapter.setNewData(mListSubData);  //添加数据
            mAdapter.loadMoreComplete();//刷新
            return;
        }
    }

    @Override
    public void onRefresh() { //刷新事件
        mAdapter.setEnableLoadMore(false); //设置禁止滑动
        ini();
        mSwipeRefresh.setRefreshing(false);
        mAdapter.setEnableLoadMore(true);
    }

    /**
     * 设置滑动事件
     **/
    private void set_huodong() {
        OnItemDragListener onItemDragListener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "drag start");
                //   BaseViewHolder holder = ((BaseViewHolder) viewHolder);

            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {
                Log.d(TAG, "move from: " + source.getAdapterPosition() + " to: " + target.getAdapterPosition());
            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "drag end");
                //   BaseViewHolder holder = ((BaseViewHolder) viewHolder);
            }
        };

        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "view swiped start: " + pos);
                //   BaseViewHolder holder = ((BaseViewHolder) viewHolder);
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "View reset: " + pos);
                //   BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
            }

            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "View Swiped: " + pos);
            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(getActivity(), R.color.color_light_blue));
            }
        };
        ItemDragAndSwipeCallback itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback);
        itemTouchHelper.attachToRecyclerView(mRecyclerView);
        //设置滑动方向
        itemDragAndSwipeCallback.setSwipeMoveFlags(itemTouchHelper.START | itemTouchHelper.END);
// 开启拖拽
        mAdapter.enableDragItem(itemTouchHelper, R.id.all_itme, true);
        mAdapter.setOnItemDragListener(onItemDragListener);
// 开启滑动删除
        mAdapter.enableSwipeItem();
        mAdapter.setOnItemSwipeListener(onItemSwipeListener);
    }

    private boolean popBoolean=true;
    /**
     * 弹出框
     **/
    private void pop(final InventorySub inventorySub) {
        if(popBoolean){
                popBoolean=false;

        //创建布局
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        View view = layoutInflater.inflate(R.layout.popup_powe_rec, null);
        final PopupWindow mPopupWindow = new PopupWindow(view, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setAnimationStyle(R.style.popup_window);
        mPopupWindow.setContentView(view);

        ImageView lmage = (ImageView) view.findViewById(R.id.lmg_xxxx);
        final TextView tv1 = (TextView) view.findViewById(R.id.pop_tv1);
        TextView tv2 = (TextView) view.findViewById(R.id.pop_tv2);
        TextView tv3 = (TextView) view.findViewById(R.id.pop_tv3);
        Button but1 = (Button) view.findViewById(R.id.button1);
        Button but2 = (Button) view.findViewById(R.id.button2);
        tv2.setText(inventorySub.getCode().toString());
        tv3.setText(inventorySub.getBarode());
        lmage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
                popBoolean=true;

            }
        });

        but1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
                popBoolean=true;
            }
        });

        but2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_showDialog("删除");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int sj = Integer.parseInt(inventorySub.getSjnumber().toString());
                        mDBManager.deleteIdNull(inventorySub.getId());
                        mListSubData.clear();
                        mListSubData = mDBManager.findSubTaskList();
                        set_ColseDialog();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mPopupWindow.dismiss();
                                popBoolean=true;
                            }
                        });

                        set_Message(0, "清空");
                    }
                }).start();
            }
        });
        WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();//创建当前界面的一个参数对象
        params.alpha = 0.8f;
        getActivity().getWindow().setAttributes(params);//把该参数对象设置进当前界面中
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
                params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                getActivity().getWindow().setAttributes(params);
            }
        });
        //第一个参数为父View对象，即PopupWindow所在的父控件对象，第二个参数为它的重心，后面两个分别为x轴和y轴的偏移量
        mPopupWindow.showAtLocation(layoutInflater.inflate(R.layout.activity_main, null), Gravity.CENTER, 0, 0);

        }
    }

    @OnClick({R.id.but_submit, R.id.but_complete, R.id.search_lmag})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_lmag:
                final String ed = mEtSearch.getText().toString();
                if (!ed.equals("")) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (ed.length() == 5) {
                                mListSubData.clear();
                                mListSubData = mDBManager.findLocationTaskSubList(ed);

                                set_Message(0, "更新UI");
                            } else {
                                mListSubData.clear();
                                mListSubData = mDBManager.findBarodeSubTaskList(ed);
                                if (mListSubData != null) {
                                    set_Message(0, "更新UI");
                                } else {
                                    set_Message(0, "清空");
                                }

                            }
                        }
                    }).start();

                } else {
                    set_Message(0, "清空");
                }
                break;
            case R.id.but_submit:
                ini();
                break;
            case R.id.but_complete:

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                            daoChu();

                    }
                }).start();
                break;
        }
    }

    private List<InventoryTaskSub> mSubListXiang;

    private void daoChu() {
        mSubListXiang = mDBManager.findTaskSubListXiang();
        try {
            mProgressDialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mSubListXiang != null && mSubListXiang.size() > 0) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(getActivity(), SameActivity.class);
                    startActivity(intent);
                }
            });
        } else {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    export();
                }
            });

        }

    }

    private PeopleRecyclerAdapter peopleRecyclerAdapter;

    private void export() {

        final ProgressDialog progressDialog = ProgressDialog.show(mContext, "", "正在导出数据请稍等");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                File file = Directory.getExcelFile();
                try {
                    List<InventoryTaskSub> subDataList = mDBManager.findTaskSubList();
                    peopleRecyclerAdapter = new PeopleRecyclerAdapter();
                    peopleRecyclerAdapter.add(new People("库位", "条码", "款式", "实际数", "多于", "差异", "盘点数", "实际数总数", "多于数总数", "差异数总数", "盘点数总数"));
                    for (int i = 0; i < subDataList.size(); i++) {
                        if (i == 0) {
                            int mDiscNumber = 0;
                            int mMoreThan = 0;
                            int mLessThan = 0;
                            int mSjnumber = 0;

                            for (int j = 0; j < subDataList.size(); j++) {
                                int discNumber = subDataList.get(j).getDiscNumber();
                                mDiscNumber = mDiscNumber + discNumber;

                                int moreThan = subDataList.get(j).getMoreThan();
                                mMoreThan = mMoreThan + moreThan;

                                int lessThan = subDataList.get(j).getLessThan();
                                mLessThan = mLessThan + lessThan;

                                int sjnumber = Integer.parseInt(subDataList.get(j).getSjnumber());
                                mSjnumber = mSjnumber + sjnumber;

                            }

                            peopleRecyclerAdapter.add(new People
                                    ((subDataList.get(i).getLocation()), (subDataList.get(i).getBarode()), (subDataList.get(i).getCode()),
                                            (subDataList.get(i).getSjnumber() + ""), (subDataList.get(i).getMoreThan() + ""), (subDataList.get(i).getLessThan() + "")
                                            , (subDataList.get(i).getDiscNumber() + ""), (mSjnumber + ""), (mMoreThan + ""), (mLessThan + ""), (mDiscNumber + "")));
                        } else {

                            peopleRecyclerAdapter.add(new People
                                    ((subDataList.get(i).getLocation()), (subDataList.get(i).getBarode()), (subDataList.get(i).getCode()),
                                            (subDataList.get(i).getSjnumber() + ""), (subDataList.get(i).getMoreThan() + ""), (subDataList.get(i).getLessThan() + "")
                                            , (subDataList.get(i).getDiscNumber() + "")));
                        }
                    }
                    ExcelUtils.write(file, peopleRecyclerAdapter.getPeoples());
                } catch (final IOException e) {
                    e.printStackTrace();

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });


                    return null;
                } catch (final WriteException e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    return null;
                }
                return file.getAbsolutePath();
            }

            @Override
            protected void onPostExecute(String path) {
                progressDialog.dismiss();
                if (TextUtils.isEmpty(path))
                    Toast.makeText(mContext, "Gagal mengekspor", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(mContext, "Berhasil mengekspor" + path, Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }
}
